package com.platform.server.util;

import com.alibaba.druid.support.json.JSONUtils;
import com.platform.server.exception.AbstractException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class ResponseUtils {

    static final Logger logger = Logger.getLogger(ResponseUtils.class);

    public static String DEFAULT_ENCODING = "UTF-8";

    public static final String TOKEN = "access_token";

    public static String DEFAULT_JSONP = "jsoncallback";

    public static final String RESPONSE_CODE = "code";
    public static final String RESPONSE_MSG = "msg";
    public static final String RESPONSE_DATA = "data";
    public static final String RESPONSE_TOTAL = "total";

    /**
     * 以秒为单位
     */
    public static final int CACHE_5_MINUTE = 5 * 60;

    /**
     * 设置content-type
     * header以及响应编码,编码从response中的getCharacterEncoding获取编码，如果此编码为空则设置为默认编码（默认为UTF
     * -8）
     * 
     * @param response
     *            http响应
     */
    public static void setContentTypeHeader(HttpServletResponse response) {
        String encoding = response.getCharacterEncoding();
        if (StringUtils.isEmpty(encoding)) {
            encoding = DEFAULT_ENCODING;
            response.setCharacterEncoding(encoding);
        }
        response.setContentType("text/html;charset=" + encoding);
    }

    /**
     * 设置不缓存响应头
     * 
     * @param response
     *            HTTP响应
     */
    public static void setNoCacheHeader(HttpServletResponse response) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache,no-store");
        response.setDateHeader("Expires", 0);
    }

    /**
     * 设置响应的内容类型及编码，同时设置不缓存的头信息
     * 
     * @param response
     */
    public static void setHtmlContentNoCacheHeader(HttpServletResponse response) {
        setContentTypeHeader(response);
        setNoCacheHeader(response);
    }

    /**
     * 设置缓存响应头
     * 
     * @param response
     * @param seconds
     *            大于0的缓存时间，单位：秒
     */
    public static void setCacheHeader(HttpServletResponse response, int seconds) {
        if (seconds <= 0) {
            return;
        }
        response.setHeader("Cache-Control", "mag-age=" + seconds);
        response.setDateHeader("Last-Modified", System.currentTimeMillis());
        response.setDateHeader("Expires", System.currentTimeMillis() + seconds * 1000);
    }

    public static void setHtmlContentCacheHeader(HttpServletResponse response, int seconds) {
        setContentTypeHeader(response);
        setCacheHeader(response, seconds);
    }

    /**
     * 向客户端写响应内容
     * 
     * @param response
     *            http响应
     * @param content
     *            需要写到浏览器的响应内容
     */
    public static void writeResponse(HttpServletRequest request, HttpServletResponse response, String content) {
        Writer writer = null;
        try {
            String jsoncallback = request.getParameter(DEFAULT_JSONP);
            // if (!WebTool.checkCallbackName(jsoncallback, response)) {
            // return;
            // }
            setContentTypeHeader(response);
            writer = response.getWriter();
            if (StringUtils.isBlank(jsoncallback)) {
                writer.write(content);
            } else {
                writer.write(jsoncallback + "(" + content + ")");
            }
        } catch (IOException e) {
            logger.error("write response error", e);
        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    logger.error("close response error", e);
                }
            }
        }
    }

    public static void writeErrorResponse(HttpServletRequest request, HttpServletResponse response,
                                          AbstractException ex) {
        setNoCacheHeader(response);
        writeResponse(request, response, ex.getCode(), ex.getMessage(), null);
    }

    public static void writeResponse(HttpServletRequest request, HttpServletResponse response, int code, String msg,
                                     Object data) {
        Map<String, Object> result = new HashMap<String, Object>();
        result.put(RESPONSE_CODE, code);
        result.put(RESPONSE_MSG, msg);
        result.put(RESPONSE_DATA, data);
        writeResponse(request, response, JSONUtils.toJSONString(result));// ,SerializerFeature.BrowserCompatible));
    }

    public static String getDefaultJsonp() {
        return DEFAULT_JSONP;
    }

    /**
     * 设置默认的JSONP的回调函数参数名
     * 
     * @param jsoncallback
     */
    public static void setDefaultJsonp(String jsoncallback) {
        DEFAULT_JSONP = jsoncallback;
    }

    /**
     * 刷新页面
     * 
     * @param request
     * @param response
     */
    public static void refreshParent(HttpServletRequest request, HttpServletResponse response) {
        String html = "<script>parent.location.reload();</script>";
        writeResponse(request, response, html);
    }

    public static boolean isAjax(HttpServletRequest request) {
        if (request.getRequestURI().endsWith(".json")) {
            return true;
        }
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }

	
}
